package com.nf.health.app.login.activity;

import android.content.Intent;
import android.graphics.Paint;
import android.os.Bundle;
import android.os.Handler;
import android.text.Editable;
import android.text.TextPaint;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.nf.health.app.R;
import com.nf.health.app.activity.global.BaseActivity;
import com.nf.health.app.activity.global.MainActivity;
import com.nf.health.app.activity.global.RegistrationActivity;
import com.nf.health.app.db.DbManager;
import com.nf.health.app.models.AJAXLogin;
import com.nf.health.app.models.UserInfo;
import com.nf.health.app.utils.ActivityUtils;
import com.nf.health.app.utils.EmUtil;
import com.nf.health.app.utils.LogUtil;
import com.nf.health.app.utils.PreferenceHelper;
import com.nf.health.app.utils.Util;

import java.util.Set;

import cn.jpush.android.api.JPushInterface;
import cn.jpush.android.api.TagAliasCallback;

/**
 * @author Ian
 * @ClassName: LoginActivity
 * @Description: 登录页面
 * @date 2015-11-4 上午9:54:26
 */
public class LoginActivity extends BaseActivity implements OnClickListener {
    protected static final String TAG = LoginActivity.class.getSimpleName();
    private EditText userNameET;
    private EditText passwordET;
    private Button submitBT;
    private TextView foget_pwd;

    private ImageView iv_delete_account, iv_delete_user;
    int count = 0;
    private static final int MSG_SET_ALIAS = 1001;
    private final Handler mHandler = new Handler() {
        @Override
        public void handleMessage(android.os.Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case MSG_SET_ALIAS:
                    LogUtil.d(TAG, "Set alias in handler.");
                    // 调用 JPush 接口来设置别名。
                    JPushInterface.setAliasAndTags(getApplicationContext(),
                            (String) msg.obj,
                            null,
                            mAliasCallback);
                    break;
                default:
                    LogUtil.i(TAG, "Unhandled msg - " + msg.what);
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        hideTitleBar();
        setContent(R.layout.activity_login);
        userNameET = (EditText) findViewById(R.id.login_acc_et);
        passwordET = (EditText) findViewById(R.id.login_pwd_et);
        submitBT = (Button) findViewById(R.id.login_ok_btn);
        foget_pwd = (TextView) findViewById(R.id.login_pw_tv);
        iv_delete_account = (ImageView) findViewById(R.id.iv_delete_account);
        iv_delete_user = (ImageView) findViewById(R.id.iv_delete_user);


        TextPaint paint = foget_pwd.getPaint();
        paint.setAntiAlias(true);
        paint.setFlags(Paint.UNDERLINE_TEXT_FLAG | Paint.ANTI_ALIAS_FLAG);

        fillView();
        initListener();
    }

    private void fillView() {

        userNameET.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence arg0, int arg1, int arg2,
                                      int arg3) {

            }

            @Override
            public void beforeTextChanged(CharSequence arg0, int arg1,
                                          int arg2, int arg3) {

            }

            @Override
            public void afterTextChanged(Editable arg0) {
                if (!TextUtils.isEmpty(userNameET.getText())) {
                    iv_delete_account.setVisibility(View.VISIBLE);
                } else {
                    iv_delete_account.setVisibility(View.GONE);
                }
            }
        });
        passwordET.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence arg0, int arg1, int arg2,
                                      int arg3) {

            }

            @Override
            public void beforeTextChanged(CharSequence arg0, int arg1,
                                          int arg2, int arg3) {

            }

            @Override
            public void afterTextChanged(Editable arg0) {
                if (!TextUtils.isEmpty(passwordET.getText())) {
                    iv_delete_user.setVisibility(View.VISIBLE);
                } else {
                    iv_delete_user.setVisibility(View.GONE);
                }
            }
        });

        setHistoryAccount();
    }

    private void initListener() {
        findViewById(R.id.login_ok_btn).setOnClickListener(this);
        findViewById(R.id.login_reg_tv).setOnClickListener(this);
        foget_pwd.setOnClickListener(this);
        iv_delete_account.setOnClickListener(this);
        iv_delete_user.setOnClickListener(this);
        submitBT.setOnClickListener(this);
    }

    @Override
    public void handleActionSuccess(String actionName, Object object) {
        super.handleActionSuccess(actionName, object);
        if ("requestAJAX".equals(actionName)) {
            AJAXLogin ajaxLogin = (AJAXLogin) object;
            PreferenceHelper.putString(PreferenceHelper.TOKEN, ajaxLogin.getCode());
            //新的token 以后每次请求必须带上 直接写在HttpRequestProvider中 2016.06.04
            PreferenceHelper.putString(PreferenceHelper.ACCESS_TOKEN, ajaxLogin.getAccess_token());
            PreferenceHelper.putBoolean(PreferenceHelper.ISLOGIN, true);
            provider.requestUserInfo("userInfo");
        } else if ("userInfo".equals(actionName)) {

            UserInfo userInfo = (UserInfo) object;
            PreferenceHelper.putString(PreferenceHelper.USERNAME, userNameET.getText().toString());
            PreferenceHelper.putString(PreferenceHelper.PASSWORD, passwordET.getText().toString());
            PreferenceHelper.putString(PreferenceHelper.USERID, userInfo.getUserid());
            PreferenceHelper.putString(PreferenceHelper.USERNICK, userInfo.getNick());
            PreferenceHelper.putString(PreferenceHelper.USERRNAME, userInfo.getRname());
            PreferenceHelper.putString(PreferenceHelper.USERSEX, userInfo.getSex());
            PreferenceHelper.putString(PreferenceHelper.USERHEIGHT, userInfo.getHeight());
            PreferenceHelper.putString(PreferenceHelper.USERWEIGHT, userInfo.getWeight());
            PreferenceHelper.putString(PreferenceHelper.BIRTHDAY, userInfo.getBirthday());
            PreferenceHelper.putUser(userInfo);
            //判断是否完成过注册信息
            if (TextUtils.isEmpty(userInfo.getNick()) || TextUtils.isEmpty(userInfo.getHeight()) || TextUtils.isEmpty(userInfo.getBirthday())) {
                PreferenceHelper.putBoolean(PreferenceHelper.REGISTER_INFO_COMPLETE, false);
            }else{
                PreferenceHelper.putBoolean(PreferenceHelper.REGISTER_INFO_COMPLETE, true);
            }
            if (JPushInterface.isPushStopped(this)) {
                JPushInterface.resumePush(this);
            }
            mHandler.sendMessage(mHandler.obtainMessage(MSG_SET_ALIAS, userInfo.getUserid()));
//			PreferenceHelper.putBoolean("IS_FIRST_TIME_USE", true);
//			String nick = PreferenceHelper.getString(PreferenceHelper.USERNICK, "");
//			if (TextUtils.isEmpty(nick)) {
//				AppManager.getAppManager().finishAllActivity();
//				Bundle bundle = new Bundle();
//				bundle.putString("type", "3");
//				ActivityUtils.skipActivity(this, RegisterNickActivity.class, bundle);
//				return;
//			}

            // After logout，the DemoDB may still be accessed due to async callback, so the DemoDB will be re-opened again.
            // close it before login to make sure DemoDB not overlap
            DbManager.getInstance().closeDB();
            // 进入主页面
            Intent intent = new Intent(LoginActivity.this, MainActivity.class);
            startActivity(intent);

            final String userinfoID = userInfo.getUserid();
            new Thread(new Runnable() {
                @Override
                public void run() {
                    EmUtil.loginEM(userinfoID);
                }
            }).start();
        }
    }



    private final TagAliasCallback mAliasCallback = new TagAliasCallback() {

        @Override
        public void gotResult(int code, String alias, Set<String> tags) {
            String logs;
            switch (code) {
                case 0:
                    logs = "Set tag and alias success";
                    LogUtil.i(TAG, logs);
                    // 建议这里往 SharePreference 里写一个成功设置的状态。成功设置一次后，以后不必再次设置了。
                    break;
                case 6002:
                    logs = "Failed to set alias and tags due to timeout. Try again after 60s.";
                    LogUtil.i(TAG, logs);
                    // 延迟 60 秒来调用 Handler 设置别名
                    mHandler.sendMessageDelayed(mHandler.obtainMessage(MSG_SET_ALIAS, alias), 1000 * 60);
                    break;
                default:
                    logs = "Failed with errorCode = " + code;
                    LogUtil.e(TAG, logs);
            }
        }

    };

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.login_ok_btn:
                String username = userNameET.getText().toString();
                String password = passwordET.getText().toString();
                if (TextUtils.isEmpty(username)) {
                    showToast("用户名不能为空");
                    return;
                }
                if (TextUtils.isEmpty(password)) {
                    showToast("密码不能为空");
                    return;
                }
                provider.requestAJAX(username, Util.encode(password), "requestAJAX");
                break;
            case R.id.login_reg_tv:
                //注册
                Bundle bundle = new Bundle();
                bundle.putString("type", "123");
                ActivityUtils.showActivity(this, RegistrationActivity.class, bundle);
                break;
            case R.id.login_pw_tv:
                ActivityUtils.showActivity(this, ForgetPasswordsActivity.class);
                break;
            case R.id.iv_delete_account:
                userNameET.setText(null);
                break;
            case R.id.iv_delete_user:
                passwordET.setText(null);
                break;
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        setHistoryAccount();
    }

    private void setHistoryAccount() {
        //注册时没有填写个人信息就返回,自动赋值
        String password = PreferenceHelper.getString(PreferenceHelper.PASSWORD, "");
        String username = PreferenceHelper.getString(PreferenceHelper.USERNAME, "");
        if (TextUtils.isEmpty(username) || TextUtils.isEmpty(password)) {
            return;
        }
        if (username.length() > 11) {
            //临时用户的userid长度大于11位
            return;
        }
        userNameET.setText(username);
        passwordET.setText(password);
        userNameET.setSelection(username.length());
        passwordET.setSelection(password.length());
    }
}
